<template>
    <n-scrollbar x-scrollable style="max-height: 100vh">
      <CommonPage show-footer>
        <div>
          <n-form ref="form"
            :model="searchCondition"
            label-placement="left"
            label-align="right"
            label-width="80px"
            :show-require-mark="false">
            <div>
              <div class="grid md:flex md:flex-wrap md:gap-x-1">
                <n-form-item style="margin-left: 10px;">
                  <label style="width: 70px;">仓库名：</label>
                  <n-select
                      v-model:value="searchCondition.storeId"
                      :options="stores"
                      placeholder="选择类型"
                      filterable
                  />
                </n-form-item>
                <n-form-item style="margin-left: 10px;">
                  <label style="width: 60px;">客户：</label>
                  <n-select
                      v-model:value="searchCondition.customersId"
                      :options="customers"
                      placeholder="选择类型"
                      filterable
                  />
                </n-form-item>
                <n-form-item style="margin-left: 10px;">
                  <label style="width: 100px;">订单负责人：</label>
                  <n-select
                      v-model:value="searchCondition.adminId"
                      :options="admins"
                      placeholder="选择类型"
                      filterable
                  />
                </n-form-item>
                <n-form-item style="margin-left: 10px;">
                  <label style="width: 60px;">商品名：</label>
                  <n-input v-model:value="searchCondition.productName" placeholder="" style="width: 150px"></n-input>
                </n-form-item>
                <n-form-item style="margin-left: 10px;">
                  <n-button type="primary"  @click="searchByCondition">筛选</n-button>
                </n-form-item>
                <n-form-item style="margin-left: 10px;">
                  <n-button type="primary" @click="test">添加出库单</n-button>
                </n-form-item>
                <n-form-item  style="margin-left: 10px">
                  <n-button type="error" @click="deleteSelectOutboundDocuments">批量删除</n-button>
                </n-form-item>
                <n-form-item style="margin-left: 10px">
                  <n-button type="primary" @click="exportListInfo">导出</n-button>
                </n-form-item>
              </div>
            </div>
          </n-form>
          <AddOutboundDocument
              :stores="filteredStores"
              :storeCommodity="filteredStoreCommodity"
              :customers="filteredCustomers"
              :admins="filteredAdmins"
              :option="option"
              @update-page="searchByCondition"
              :show="showForm1"
              :onClose="handleClose"/>
          <UpdateOutboundDocument
              :stores="filteredStores"
              :storeCommodity="filteredStoreCommodity"
              :customers="filteredCustomers"
              :admins="filteredAdmins"
              :option="option"
              :quantityBefore="quantity"
              @update-page="searchByCondition"
              :show="showForm"
              :onClose="handleClose"
              :attribute="currentAttribute"
          />
          <n-data-table
              remote
              :single-line="false"
              ref="table"
              :columns="columns"
              :data="storeReceiptList"
              :loading="loading"
              :pagination="paginationReactive"
              :row-key="rowKey"
              :header-cell-style="{ textAlign: 'center' }"
              :cell-style="{ textAlign: 'center' }"
              @update:checked-row-keys="handleCheck"
          />
        </div>
      </CommonPage>
    </n-scrollbar>
</template>
<script setup>
import {onMounted, reactive, ref} from 'vue'
import api from '@/api/admin';
import {useUserStore} from '@/store';
import {useRouter} from 'vue-router';
import {formatDate} from "@/utils";
import InventoryActions from "@/views/admin/category/components/category-actions.vue";
import AddOutboundDocument from "@/views/admin/inventory/components/goods-out.vue"
import UpdateOutboundDocument from "../components/goods-out-edit.vue"

const userStore = useUserStore()
const router = useRouter()
const loading = ref(true)
const range = ref(null)
const showForm1=ref(false)
const showForm=ref(false)
const value = ref("全部")
const storeReceiptList = ref([])
const checkedRowKeysRef = ref([]);
const option = ref([])
const currentAttribute = ref(null); // 当前编辑的属性
const quantity=ref('');

const handleClose = () => {
  showForm1.value = false;
  showForm.value = false;
};
const handleCheck = (rowKeys) => {
  checkedRowKeysRef.value = rowKeys;
}
const test = () => {
  showForm1.value = true;
};

const stores = ref([])
stores.value.push({
  label:'全部',
  value:-1,
})
const storeCommodity = ref([])
storeCommodity.value.push({
  label:'全部',
  value:-1,
})
const customers = ref([])
customers.value.push({
  label:'全部',
  value:-1,
})
const admins = ref([])
admins.value.push({
  label:'全部',
  value:-1,
})
const columns = [
  {
    type: 'selection',
    fixed: 'left',
  },
    {
        key: 'colId',
        title: '序号',
        width: 60,
    },
  {
    key: 'id',
    title: '编号',
    width: 60,
  },
    {
        key: 'storeName',
        title: '出库仓库',
        width: 100,

    },
    {
        key: 'storeCommodityName',
        title: '出库货品',
        width: 200,
    },
    {
        key: 'objectName',
        title: '客户',
        width: 100,

    },

    {
        key: 'price',
        title: '价格',
        width: 80,
    },
    {
        key: 'quantity',
        title: '数量',
        width: 80,
    },
    {
        key: 'adminName',
        title: '订单负责人',
        width: 100,
    },
    {
        key: 'createTime',
        title: '创建时间',
        width: 100,
    },
    {
        key: 'do',
        title: '操作',
        width: 120,
        render(row) {
            return h(
                InventoryActions,
                {
                    onClickEdit: () => onEditOutBoundDocument(row),
                    onClickDelete: () => onDeleteOutBoundDocument(row),
                }
            );
        }
    },
]

// 过滤掉 '全部' 选项
const filteredStores = computed(() => stores.value.filter(store => store.value !== -1));
const filteredStoreCommodity = computed(() => storeCommodity.value.filter(commodity => commodity.value !== -1));
const filteredCustomers = computed(() => customers.value.filter(customers => customers.value !== -1));
const filteredAdmins = computed(() => admins.value.filter(admin => admin.value !== -1));

let total = 0
const paginationReactive = reactive({
    page: 1,
    pageSize: 50,
    showSizePicker: true,
    pageSizes: [50, 100, 150],
    itemCount:0,
    prefix: () => {
        return '查询出 ' + total + '条记录';
    },
    onChange: (page) => {
        paginationReactive.page = page;
        queryByPage()
    },
    onUpdatePageSize: (pageSize) => {
        paginationReactive.pageSize = pageSize;
        paginationReactive.page = 1;
        queryByPage()
    }
});
const searchCondition=ref(
	{
		storeId: -1,
		customersId: -1,
		adminId: -1,
		productName: '',
		type: 'outbound'
	}
)
const searchByCondition = async ()=>{
	loading.value = true
	try {
		paginationReactive.page = 1;
		const res = await api.findPageStoreReceipt({
			params: {
				...searchCondition.value,
				pageNum: paginationReactive.page,
				pageSize: paginationReactive.pageSize,
			}
		})
		if (res.code === 200) {
			total = res.data.total
			paginationReactive.itemCount = total
			const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
			storeReceiptList.value = res.data.records.map((item,i)=>{
				return {...item,
					colId: baseCount + i + 1,
				}
			})
		} else {
			$message.error(res.message)
		}
	} catch (err) {
		$message.error("查询出库单失败！")
	} finally {
		loading.value = false
	}
}
const onDeleteOutBoundDocument = async (outBoundDocument) => {
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前出库单？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const {id} = outBoundDocument
      loading.value = true
      try {
        const res = await api.deleteOutBoundDocument({id})
        if(res.code === 200) {
          $message.success("删除出库单成功！")
          await searchByCondition()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除出库单失败！")
      }finally{
        loading.value = false
      }
    }
  })
}
const deleteSelectOutboundDocuments = () => {
  if(checkedRowKeysRef.value.length <= 0) {
    console.log(checkedRowKeysRef.value.length)
    $message.error("当前并未选择出库单！")
    return
  }
  $dialog.confirm({
    title: '警告',
    content: '您确定删除当前所选出库单？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const ids = checkedRowKeysRef.value.join(",")
      loading.value = true
      try {
        const res = await api.deleteOutBoundDocuments({params:{ids}})
        if(res.code === 200) {
          $message.success("删除所选出库单成功！")
          await searchByCondition()
        }
        else {
          $message.error(res.message)
        }
      } catch (err) {
        $message.error("删除所选出库单失败！")
      }finally{
        loading.value = false
      }
    },
  })
}

const onEditOutBoundDocument = async (outBoundDocument) => {
  quantity.value = outBoundDocument.quantity;
  currentAttribute.value = outBoundDocument; // 设置当前编辑的属性
  showForm.value = true; // 显示编辑窗口
}

const onDetailLog = async (log)=>{
    const {id} = log
    await router.push({name: 'AdminLogDetail', params: {logId: id}});
}
const queryStoreList = async () => {
  loading.value = true
  try {
    const res = await api.findAllStore()
    if(res.code === 200) {
      res.data.map((item)=>{
        stores.value.push({
          label: item.name,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取仓库信息失败！")
  }finally{
    loading.value = false
  }
}
const queryStoreCommodityList = async () => {
  loading.value = true
  try {
    const res = await api.findAllInventory()
    if(res.code === 200) {
      res.data.map((item)=>{
        storeCommodity.value.push({
          label: item.productName,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取货物信息失败！")
  }finally{
    loading.value = false
  }
}
const queryCustomersList = async () => {
  loading.value = true
  try {
    const res = await api.findAllCustomer()
    if(res.code === 200) {
      res.data.map((item)=>{
        customers.value.push({
          label: item.name,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取客户信息失败！")
  }finally{
    loading.value = false
  }
}
const queryAdminList = async () => {
  loading.value = true
  try {
    const res = await api.findAdminsInboundDocument()
    if(res.code === 200) {
      res.data.map((item)=>{
        admins.value.push({
          label: item.name,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取管理员信息失败！")
  }finally{
    loading.value = false
  }
}

const queryByPage = async ()=>{
	loading.value = true
	try {
		const res = await api.findPageStoreReceipt(
			{
				params: {
					type: searchCondition.value.type,
					pageNum:paginationReactive.page,
					pageSize:paginationReactive.pageSize,
				}
			})
		if(res.code === 200) {
			total = res.data.total
			paginationReactive.itemCount = total
			storeReceiptList.value = res.data.records.map((item,i)=>{
				return {...item,
					colId: i+1
				}
			})
			$message.success("获取出库单成功！")
		}
		else {
			$message.error(res.message)
		}
	} catch (err) {
		$message.error("获取出库单失败！")
	}finally{
		loading.value = false
	}
}
const exportListInfo = async () => {
  const res = await api.exportStoreReceiptList({
    adminId: searchCondition.value.adminId.toString(),
    storeId: searchCondition.value.storeId.toString(),
    objectId: searchCondition.value.customersId.toString(),
    productName: searchCondition.value.productName,
    type: searchCondition.value.type,
  });
  const contentDisposition = res.headers["content-disposition"]
  let original_fileName = ""
  if (contentDisposition) {
    const uri = res.headers["content-disposition"].split("=")[1]
    original_fileName = window.decodeURI(uri)
  }
  const blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, original_fileName);
  } else {
    const fileName = original_fileName;
    const elink = document.createElement('a')
    document.body.appendChild(elink)
    elink.style.display = 'none'
    const href = window.URL.createObjectURL(blob)
    elink.href = href
    elink.download = fileName
    elink.click()
    window.URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  }
}
const rowKey = (rowData) => {
    return rowData.id
}
onMounted(()=>{
  queryStoreList()
  queryCustomersList()
  queryStoreCommodityList()
  queryAdminList()
  queryByPage()
})
</script>
<style scoped>
:deep(.n-data-table-th__title),
:deep(.n-data-table-td) {
    text-align: center;

}
:deep(.n-select) {
    width: 140px !important;
}
:deep(.two-line-description) {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2; /* 控制显示的行数 */
    overflow: hidden;
}
</style>
